import React, { useState, useEffect } from 'react';
import { Button, Card, Divider, Row, Col, Checkbox, DatePicker } from 'antd';
import { BaseTable, utils } from '@/components/BaseTable';
import router from 'umi/router';
import moment from 'moment';
import _ from 'lodash';
import { connect } from 'dva';
import PageEmpty from '@/components/PageEmpty';
import { handlerMatomoEvent } from '@/utils/matomo';
import { getTitleTree, getFixedColumns } from './utils/tableUtils';
import styles from './index.less';

const CheckboxGroup = Checkbox.Group;
const VersionComparison = props => {
  const { items, expandedRowKeys, dispatch, location } = props;
  const [state, setState] = useState({
    attributesChecked: ['套数', '面积', '均价', '金额'], // 选中的多选框
    titleTree: [], // table 头部数据
    deadline: moment().format('YYYY-MM'), // 选中的截至年月
    emptyTitle: '加载中...',
  });

  // 请求供货对比接口方法
  const requestSupplyContrast = (deadline = moment().format('YYYY-MM')) => {
    const { projectId } = location.query;
    dispatch({
      type: 'VersionComparisonItems/init',
      payload: {
        params: {
          deadline,
          projectId,
        },
      },
      callback: () => {
        setState({
          ...state,
          emptyTitle: '暂无对比结果！',
        });
      },
    });
  };

  useEffect(() => {
    // 供货计划对比 埋点处理
    handlerMatomoEvent({
      category: 'Page',
      action: '供货计划对比',
      name: '供货计划对比',
    });
    // 第一次加载数据调用供货对比接口方法
    requestSupplyContrast();
    // 默认显示表格头部
    const titleTree = getTitleTree(state.attributesChecked, state.deadline);
    setState({
      ...state,
      titleTree,
    });
  }, []);

  // 监听多选框的改变状态
  const onChangeAttributesChecked = checkedValues => {
    // 显示筛选的表头
    const titleTree = getTitleTree(checkedValues, state.deadline);
    setState({
      ...state,
      titleTree,
      attributesChecked: checkedValues,
    });
  };

  // 获取截至日期做数据操作
  const handleDeadline = (field, value) => {
    // 切换截至日期调用供货对比接口方法
    requestSupplyContrast(value);
    // 切换表头年份
    const titleTree = getTitleTree(state.attributesChecked, value);
    setState({
      ...state,
      titleTree,
      deadline: value,
    });
  };

  // state 变量集合
  const { attributesChecked, deadline, titleTree, emptyTitle } = state;
  // dom节点
  const element = (
    <div className={styles.VersionComparison}>
      <header className="header">{`${unescape(props.location.query.projectName)}供货对比`}</header>
      <div className="content">
        <Card>
          <Row type="flex" align="middle" justify="space-between">
            <Col>
              <div className="sub_title">
                <i></i>
                <span>对比结果</span>
              </div>
            </Col>
            <Col>
              <Row type="flex" align="middle" justify="space-between" gutter={[30, 0]}>
                <Col>
                  <CheckboxGroup
                    options={['套数', '面积', '均价', '金额']}
                    value={attributesChecked}
                    onChange={onChangeAttributesChecked}
                  />
                </Col>
                <Col>
                  <span>截止年月&nbsp;:&nbsp;</span>
                  <DatePicker.MonthPicker
                    allowClear={false}
                    onChange={handleDeadline}
                    defaultValue={moment(deadline)}
                    format="YYYY-MM"
                    disabledDate={current => current && current > moment().endOf('day')}
                  />
                </Col>
              </Row>
            </Col>
          </Row>
          {items && !_.isEmpty(items) ? (
            <BaseTable
              subtractHeight="187px"
              defaultExpandedRowKeys={expandedRowKeys}
              expandColumnKey="name"
              fixedColumns={getFixedColumns(deadline, attributesChecked)}
              headerHeight={[30, 30, 60]}
              headerRenderer={utils.getHeaderRenderer(titleTree, 2)}
              treeData={items}
            />
          ) : (
            <div className="loading">
              <PageEmpty emptyTitle={emptyTitle} />
            </div>
          )}
          <Divider />
        </Card>
      </div>
      <div className="header">
        <Button type="primary" onClick={() => router.go(-1)}>
          关闭
        </Button>
      </div>
    </div>
  );

  return element;
};

export default connect(state => ({
  items: state.VersionComparisonItems.items,
  expandedRowKeys: state.VersionComparisonItems.expandedRowKeys,
}))(VersionComparison);
